package model

import (
	"gin/database"
	"github.com/Gre-Z/common/jtime"
	teamones_helper "github.com/teamones-open/go-helper"
	"gorm.io/datatypes"
	"strings"
)

type Monolog struct {
	Id           int64            `json:"id" gorm:"column:id"`
	Level        string           `json:"level" gorm:"column:level"`
	Route        string           `json:"route" gorm:"column:route"`
	RequestParam datatypes.JSON   `json:"request_param" gorm:"column:request_param"`
	Record       string           `json:"record" gorm:"column:record"`
	BelongSystem string           `json:"belong_system" gorm:"column:belong_system"`
	Created      jtime.TstampTime `json:"created" gorm:"column:created"`
}

// 设置表名
func (Monolog) TableName() string {
	return "monolog"
}

func (this *Monolog) Insert() (id int64, err error) {
	result := Mysql.DB.Create(&this)
	id = this.Id
	if result.Error != nil {
		err = result.Error
		return
	}
	return
}

func (this *Monolog) Find(Param teamones_helper.SelectQueryParam) (resData Monolog, err error) {

	logOne := new(Monolog)
	db := Mysql.DB

	// 组装过滤条件
	if Param.Where != nil {
		for key, val := range Param.Where {
			vals := val.(map[string]interface{})
			if strings.Contains(key, "bw_") {
				db = db.Where(vals["condition"], vals["val1"], vals["val2"])
			} else {
				db = db.Where(vals["condition"], vals["val"])
			}
		}
	} else {
		db = db.Where("?", "1=1")
	}

	// 应用分页
	db = db.Select(Param.Fields)

	result := db.First(&logOne)
	if result.Error != nil {
		err = result.Error
		return
	}

	return *logOne, err
}

func (this *Monolog) Select(Param teamones_helper.SelectQueryParam) (total int, resData []Monolog, err error) {

	logs := make([]Monolog, 0)
	db := Mysql.DB

	// 组装过滤条件
	if Param.Where != nil {
		for key, val := range Param.Where {
			vals := val.(map[string]interface{})
			if strings.Contains(key, "bw_") {
				db = db.Where(vals["condition"], vals["val1"], vals["val2"])
			} else {
				db = db.Where(vals["condition"], vals["val"])
			}
		}
	} else {
		db = db.Where("?", "1=1")
	}

	// 获取总条数
	db.Model(this).Count(&total)

	// 查找所有数据

	// 应用分页
	db = db.Select(Param.Fields).Limit(Param.Limit).Offset(Param.Offset)

	// 应用排序参数
	if Param.Order != "" {
		db = db.Order(Param.Order)
	}

	result := db.Find(&logs)
	if result.Error != nil {
		err = result.Error
		return
	}

	return total, logs, err
}
